package com.atguigu.gmall.weball.controller;

import com.atguigu.gmall.cart.vo.AddItemVo;
import com.atguigu.gmall.cart.vo.AddSuccessVo;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.cart.CartFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lfy
 * @Description
 * @create 2023-07-29 11:31
 *
 *
 * 临时购物车和用户购物车合并
 * 1、如果用户登录了，之前临时购物车的所有商品都会被移动到用户购物车，且临时购物车数据清空
 */
@Slf4j
@Controller
public class CartController {


    @Autowired
    CartFeignClient cartFeignClient;

    //如果写了一个容器（List、Set、Map）只放不删，就会oom；【ThreadLocal的原理】
//    public static final Map<Thread,HttpServletRequest> requestMap = new ConcurrentHashMap<>();


    //同一个线程共享数据用的
//    public static final ThreadLocal<HttpServletRequest>  threadLocal = new ThreadLocal<>();


    /**
     * 请求 == CartController.addToCart() === 拦截器 === cartFeignClient.addToCart == 跟远程建立链接发送数据 == service-cart
     *
     * 每个请求一进来，Tomcat会分配一个线程处理，直到请求结束
     *
     * @param vo
     * @param model
     * @return
     */
    @GetMapping("/addCart.html")
    public String addToCart(@Validated AddItemVo vo,
                            Model model){
        //请求进来，和当前线程进行绑定
//        requestMap.put(Thread.currentThread(),request);
//        threadLocal.set(request); //把当前请求共享到本地线程

        //远程调用购物车功能
        Result<Map<String, Object>> result = cartFeignClient.addToCart(vo);

        Map<String, Object> data = result.getData();
        model.addAllAttributes(data);

//        requestMap.remove(Thread.currentThread());
//        threadLocal.remove();
        return "cart/addCart";
    }


    /**
     * 购物车列表页
     * @return
     */
    @GetMapping("/cart.html")
    public String cart(){
        return "cart/index";
    }


    /**
     * 删除选中的商品
     * @return
     */
    @GetMapping("/cart/deleteChecked")
    public String deleteChecked(){

        //远程调用购物车删除选中的商品
        cartFeignClient.deleteChecked();

        return "redirect:http://cart.gmall.com/cart.html";
    }
}
